"ui";

importClass(android.graphics.Paint);

var color = "#009688";

ui.layout(
    <drawer id="drawer">
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="桌面时间" />
                <tabs id="tabs" />
            </appbar>
            <viewpager id="viewpager">
                {/* 界面1 */}
                <frame>
                    <card w="*" h="55" margin="10 8" cardCornerRadius="2dp"
                        cardElevation="1dp" foreground="?selectableItemBackground">
                        <horizontal gravity="center_vertical">
                            <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                <text id="set1" text="显示桌面时间" textColor="#222222" textSize="16sp" maxLines="1" />
                                <text text="控制显示隐藏桌面时间" textColor="#999999" textSize="14sp" maxLines="1" />
                            </vertical>
                            <checkbox id="set1_c" marginLeft="4" marginRight="6" checked="true" />
                        </horizontal>
                    </card>
                </frame>
                {/* 界面2 */}
                <frame>
                    <vertical>
                        <list id="todoList">
                            <card w="*" h="70" margin="10 5" cardCornerRadius="2dp"
                                cardElevation="1dp" foreground="?selectableItemBackground">
                                <horizontal gravity="center_vertical">
                                    <View bg="{{this.color}}" h="*" w="10" />
                                    <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                        <text id="title" text="{{this.title}}" textColor="#222222" textSize="16sp" maxLines="1" />
                                        <text text="{{this.summary}}" textColor="#999999" textSize="14sp" maxLines="1" />
                                    </vertical>
                                    <checkbox id="done" marginLeft="4" marginRight="6" checked="{{this.active}}" />
                                </horizontal>

                            </card>
                        </list>
                    </vertical>
                    <fab id="add" w="auto" h="auto" src="@drawable/ic_add_black_48dp"
                        margin="16" layout_gravity="bottom|right" tint="#ffffff" />
                </frame>
            </viewpager>
        </vertical>


        {/* 抽屉 */}
        <vertical layout_gravity="left" bg="#ffffff" w="280">
            <img w="280" h="200" scaleType="fitXY" src="http://images.shejidaren.com/wp-content/uploads/2014/10/023746fki.jpg" />
            <list id="menu">
                <horizontal bg="?selectableItemBackground" w="*">
                    <img w="50" h="50" padding="16" src="{{this.icon}}" tint="{{color}}" />
                    <text textColor="black" textSize="15sp" text="{{this.title}}" layout_gravity="center" />
                </horizontal>
            </list>
        </vertical>
    </drawer>
);

// 工具栏 ================================

//创建选项菜单(右上角)
ui.emitter.on("create_options_menu", menu => {
    menu.add("设置");
    menu.add("关于");
});
//监听选项菜单点击
ui.emitter.on("options_item_selected", (e, item) => {
    switch (item.getTitle()) {
        case "设置":
            toast("还没有设置功能");
            break;
        case "关于":
            alert("关于", "YinYinBB Mua~ ❤");
            break;
    }
    e.consumed = true;
});
activity.setSupportActionBar(ui.toolbar);

//设置滑动页面的标题
ui.viewpager.setTitles(["设置", "定时"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);

//让工具栏左上角可以打开侧拉菜单
ui.toolbar.setupWithDrawer(ui.drawer);

// 工具栏定义
ui.menu.setDataSource([
    {
        title: "退出",
        icon: "@drawable/ic_exit_to_app_black_48dp"
    }
]);

// 工具栏监听
ui.menu.on("item_click", item => {
    switch (item.title) {
        case "退出":
            ui.finish();
            break;
    }
})


// todo =============================
var materialColors = ["#e91e63", "#ab47bc", "#5c6bc0", "#7e57c2", "##2196f3", "#00bcd4",
    "#26a69a", "#4caf50", "#8bc34a", "#ffeb3b", "#ffa726", "#78909c", "#8d6e63"];

const timeRegex = /^([01]\d|2[0-3]):([0-5]\d)$/;

function isTimeValid(timeStr) {
    return timeRegex.test(timeStr);
}

var storage = storages.create("todoList");
//从storage获取todo列表
var todoList = storage.get("items", [
    {
        title: "12点抢奶茶",
        summary: "12:00",
        color: "#f44336",
        active: true
    }
]);;

ui.todoList.setDataSource(todoList);

// todo 列表check按钮监听
ui.todoList.on("item_bind", function (itemView, itemHolder) {
    //绑定勾选框事件
    itemView.done.on("check", function (checked) {
        let job = {
            title: itemView.title.getText(),
            active: checked
        }
        updateTodo(job)
    });
});

// 更新任务状态
function updateTodo(job){
    let item = todoList.find(todo=>todo.title === job.title);
    if(item){
        item.active = job.active;
    }
}

// todo 列表监听
ui.todoList.on("item_click", function (item, i, itemView, listView) {
    itemView.done.checked = !itemView.done.checked;
});

// todo 列表长按监听
ui.todoList.on("item_long_click", function (e, item, i, itemView, listView) {
    confirm("确定要删除" + item.title + "吗？")
        .then(ok => {
            if (ok) {
                todoList.splice(i, 1);
            }
        });
    e.consumed = true;
});

//当离开本界面时保存todoList
ui.emitter.on("pause", () => {
    storage.put("items", todoList);
});

// add 按钮监听
ui.add.on("click", () => {
    dialogs.rawInput("请输入标题")
        .then(title => {
            if (!title) {
                return;
            }
            dialogs.rawInput("请输入期限 例如 11:01", "")
                .then(summary => {
                    if(!isTimeValid(summary)){
                        toast("时间格式错误");
                        return;  
                    }
                    todoList.push({
                        title: title,
                        summary: summary,
                        color: materialColors[random(0, materialColors.length - 1)],
                        active: true
                    });
                });
        })
});

// 定时任务检测
var todoInterval = setInterval(()=>{
    var activeTodoList = todoList.filter(todo=>todo.active);
    //console.log("activeTodoList:"+JSON.stringify(activeTodoList))
    for (let i = 0; i < activeTodoList.length; i++) {
        // 获取当前任务
        var job = activeTodoList[i];
        if(job && job["active"]){
            // 如果job日期不合法，需要直接清除该job
            if(!isTimeValid(job["summary"])){
                for (let j = 0; j < todoList.length; j++) {
                    if (todoList[j].title === job["title"]) {
                        todoList.splice(j, 1);
                        j--; // 因为删除元素后索引会改变，所以需要将索引回退一位继续检查后续元素
                    }
                }
            }
            // 获取当前时间
            let currentTime = new Date();
            // 获取目标时间
            let [h, m] = job["summary"].split(':').map(Number);
            let targetTime = new Date();
            targetTime.setHours(h);
            targetTime.setMinutes(m);
            targetTime.setSeconds(0);
            targetTime.setMilliseconds(0);
            // 计算时间差（单位为毫秒）
            let diff = targetTime - currentTime;
            // 将时间差换算成秒
            let diffSeconds = Math.floor(diff / 1000);
            // 判断当前时间距离目标时间是否小于等于30秒
            console.log(job["title"]+":diffSeconds:"+diffSeconds)
            if(diffSeconds < 0){
                //console.log(job["title"]+":时间都过了");
            }else if (diffSeconds <= 60 && diffSeconds >= 40 && job["active"]) {
                //console.log(job["title"]+":当前时间距离目标时间小于等于30秒，执行相应操作");
                notify()
            }else{
                //console.log(job["title"]+":还未开始");
            }
        }
    }
},10)

// 通知方法
function notify(){
    //启动一个线程去通知
    threads.start(function(){
        device.vibrate(300);
    });
}


// 时间部分 ===================================
var xx;
try {
    checkFloatPermission();
    xx = startFloatingWindow(); // 如果权限检查通过，启动悬浮窗功能
} catch (e) {
    toast("没有悬浮窗权限，正在请求...");
    requestFloatPermission(); // 请求权限
}

// 尝试创建一个最小的悬浮窗来检测权限
function checkFloatPermission(){
    let window_t = floaty.window(
        <frame bg="#000000" alpha="0.8" padding="10dp">
            <text id="timeText" textSize="24sp" textColor="#ffffff" />
        </frame>
    );
    window_t.close(); // 如果没有权限，floaty.window 会抛出异常
}

// 请求悬浮窗权限
function requestFloatPermission() {
    app.startActivity({
        action: "android.settings.action.MANAGE_OVERLAY_PERMISSION",
        data: "package:" + currentPackage()
    });
}

// 启动悬浮窗
function startFloatingWindow() {
    // 创建悬浮窗
    let window = floaty.window(
        <frame id="frame" bg="#000000" alpha="0.8" padding="8dp">
            <text id="timeText" textSize="16sp" textColor="#ffffff" />
        </frame>
    );

    // 设置悬浮窗初始位置靠屏幕右上角
    window.setPosition(device.width-400, 0);

    // 开启拖动功能
    let x = 0, y = 0; // 记录按下时的坐标
    let windowX = 0, windowY = 0; // 记录悬浮窗初始位置
    window.timeText.setOnTouchListener((view, event) => {
        switch (event.getAction()) {
            case event.ACTION_DOWN: // 手指按下
                // 记录按下位置
                x = event.getRawX();
                y = event.getRawY();
                windowX = window.getX();
                windowY = window.getY();

                // 设置按住效果
                ui.run(() => {
                    window.frame.setBackgroundColor(colors.parseColor("#555555")); // 改变背景颜色
                });

                return true;

            case event.ACTION_MOVE: // 手指移动
                let dx = event.getRawX() - x; // X轴移动距离
                let dy = event.getRawY() - y; // Y轴移动距离
                window.setPosition(windowX + dx, windowY + dy); // 更新悬浮窗位置
                return true;

            case event.ACTION_UP: // 手指抬起
                // 恢复原始背景颜色
                ui.run(() => {
                    window.frame.setBackgroundColor(colors.parseColor("#000000")); // 恢复原色
                });

                return true;
        }
        return false;
    });

    // 每隔 1 毫秒更新时间
    let interval = setInterval(() => {
        let currentTime = new Date();
        let timeString = formatTime(currentTime);

        // 使用主线程更新 UI
        ui.run(() => {
            window.timeText.setText(timeString);
        });
    }, 10);

    this.closeWindow = () =>{
        clearInterval(interval);
        window.close();
    }
}

// 时间格式化函数
function formatTime(date) {
    let hours = padZero(date.getHours());
    let minutes = padZero(date.getMinutes());
    let seconds = padZero(date.getSeconds());
    let milliseconds = padMilliseconds(date.getMilliseconds());
    return `${hours}:${minutes}:${seconds}.${milliseconds}`;
}

// 两位补零函数
function padZero(num) {
    return num < 10 ? "0" + num : num;
}

// 三位补零函数
function padMilliseconds(ms) {
    if (ms < 10) return "00" + ms;
    if (ms < 100) return "0" + ms;
    return ms;
}

// 设置部分=======================================
//绑定勾选框事件

ui.set1_c.on("check", function (checked) {
    if (checked) {
        toast("暂时不支持该功能！")
    } else {
        toast("暂时不支持该功能！")
    }
});






// 保留调试代码 ===========================
// ui 列表筛选组件
function debug(){
    // 获取List组件
    var listView = ui.todoList;
    // 获取List组件中的子视图数量
    var childCount = listView.getChildCount();
    // 遍历List组件中的每个子视图
    for (var i = 0; i < childCount; i++) {
        var childView = listView.getChildAt(i);
        console.log(childView.done.checked)
        updateChecked(childView,checked)  
    }
}

// 更新todo选中
function updateChecked(itemView,checked){
    itemView.done.checked = checked;
}
